<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.blurry" size="small" clearable placeholder="输入名称或者描述搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
<!--        <date-range-picker v-model="query.createTime" class="date-item" />-->
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!-- 表单渲染 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="520px">
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" style="width: 380px;" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDescribe">
          <el-input v-model="form.roleDescribe" style="width: 145px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
      <!--角色管理-->
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table ref="table" v-loading="crud.loading" highlight-current-row style="width: 100%;" :data="crud.data"  @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange(crud.data)">
            <el-table-column :selectable="checkboxT" type="selection" width="55" />
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="roleDescribe" label="角色描述" />
            <el-table-column :show-overflow-tooltip="true" width="135px" prop="createTime" label="创建日期">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-permission="['admin','roles:edit','roles:del']" label="操作" width="220px" align="center" fixed="right">
              <template slot-scope="scope">
                <udOperation
                  style="display: inline-block"
                  :data="scope.row"
                  :permission="permission"
                />
                <!--选择权限-->
                <el-button style="display: inline-block;" size="mini" type="primary" icon="el-icon-edit" @click="getPermission(scope.row)">权限</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </el-card>

    <!--权限勾选弹框 start-->
    <el-dialog append-to-body :close-on-click-modal="false" :destroy-on-close="true" title="勾选权限" width="321px" :visible.sync="showPermissionTree">
      <el-tree
        :default-checked-keys="selectedMenus"
        ref="roleTree"
        node-key="id"
        :props="props"
        :data="treeDataList"
        show-checkbox>
      </el-tree>
          <span slot="footer" class="dialog-footer">
         <el-button type="primary" @click="saveRoleMenus" >保存</el-button>
         </span>
    </el-dialog>
    <!--权限勾选弹框 end-->
  </div>
</template>

<script>
import crudRoles from '@/api/system/role'
import {addRoleMenus,getMenusByRole} from '@/api/system/role'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
import { getMenusTree, getChild, menusPage, subMenus } from '@/api/system/menu'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import DateRangePicker from '@/components/DateRangePicker'
import dataUtils from '@/utils/dataUtils'
import appUtils from '@/utils/appUtils'

const defaultForm = { id: null, name: null, depts: [], description: null, dataScope: '全部', level: 3,roleDescribe:null,roleName:null }
export default {
  name: 'Role',
  components: { Treeselect, pagination, crudOperation, rrOperation, udOperation, DateRangePicker },
  cruds() {
    return CRUD({ title: '角色', url: 'admin/role/page', sort: 'level,asc', crudMethod: { ...crudRoles }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      query:{
        blurry:null,
        createTime:null,
      },
      defaultProps: { children: 'children', label: 'label', isLeaf: 'leaf' },
      dateScopes: ['全部', '本级', '自定义'], level: 3,
      currentId: 0, menuLoading: false, showButton: false,
      menus: [], menuIds: [], depts: [], deptDatas: [], // 多选时使用
      permission: {
        add: ['admin', 'sys_role_add'],
        edit: ['admin', 'sys_role_edit'],
        del: ['admin', 'sys_role_del']
      },
      rules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        roleDescribe: [
          { required: true, message: '请输入具体描述', trigger: 'blur' }
        ]
      },
      /*权限树数据*/
      props: {
        /*父节点*/
        label: 'name',
        /*子节点*/
        children: 'children',
        isLeaf: 'leaf'
      },
      showPermissionTree:false,
      selectedMenus:[],
      treeDataList:[]
    }
  },
  created() {
  },
  methods: {
    getMenuDatas(node, resolve) {
      setTimeout(() => {
        getMenusTree(node.data.id ? node.data.id : 0).then(res => {
          resolve(res)
        })
      }, 100)
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空菜单的选中
        // this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
         this.currentId = val[0].id
        // 初始化默认选中的key
        this.menuIds = []
        for (let i = 0; i <val.length ; i++) {
          this.menuIds.push(val[i].id)
        }
        // val.menus.forEach(function(data) {
        //   _this.menuIds.push(data.id)
        // })
        this.showButton = true
      }
    },
    saveMenu() {
      this.menuLoading = true
      const role = { id: this.currentId, menus: [] }
      // 得到已选中的 key 值
      this.menuIds.forEach(function(id) {
        const menu = { id: id }
        role.menus.push(menu)
      })
      crudRoles.editMenu(role).then(() => {
        this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.menuLoading = false
        this.update()
      }).catch(err => {
        this.menuLoading = false
      })
    },
    // 改变数据
    update() {
      // 无刷新更新 表格数据
      crudRoles.get(this.currentId).then(res => {
        for (let i = 0; i < this.crud.data.length; i++) {
          if (res.id === this.crud.data[i].id) {
            this.crud.data[i] = res
            break
          }
        }
      })
    },
    // 获取部门数据
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getSupDepts(depts) {
      const ids = []
      depts.forEach(dept => {
        ids.push(dept.id)
      })
      getDeptSuperior(ids).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 如果数据权限为自定义则获取部门数据
    changeScope() {
      if (this.form.dataScope === '自定义') {
        this.getDepts()
      }
    },
    checkboxT(row) {
      /*修改角色权限*/
      // return row.level >= this.level
      return true
    },
    /**
     * 获取节点数据
     * /
     */
    getPermission(val){
      this.showPermissionTree=true
      dataUtils.setData("scope",val)
      this.getMenuTreeList(val)
    },

    /**
     * 保存角色菜单
     */
    saveRoleMenus(){
      /*选中的数据*/
      var menuIds=[]
      for (let i = 0; i < this.$refs.roleTree.getCheckedNodes().length; i++) {
        menuIds.push(this.$refs.roleTree.getCheckedNodes()[i])
      }
      console.log('选中',menuIds);
      let data1 = dataUtils.getData("scope");
      let parse = JSON.parse(data1);
      let data={
        checkList:menuIds,
        checkRoleId: parse.id
      }
      addRoleMenus(JSON.stringify(data)).then(res=>{
        if (res.state){
          appUtils.showSuccess(res.msg)
          this.showPermissionTree=false
        }
        else {
          appUtils.showError(res.msg)
          this.showPermissionTree=true
        }
      })
      dataUtils.removeData("scope");

    },
    /**
     * 获取菜单角色树
     */
    getMenuTreeList(data){
      let roleId=data.id;
      getMenusByRole(roleId).then(res=>{
        this.treeDataList=res.data.dataList
        this.selectedMenus=res.data.idList
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .role-span {
    font-weight: bold;color: #303133;
    font-size: 15px;
  }
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
 ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
 ::v-deep .vue-treeselect__multi-value{
    margin-bottom: 0;
  }
 ::v-deep .vue-treeselect__multi-value-item{
    border: 0;
    padding: 0;
  }
</style>
